package com.geez.bbl.linking;

import com.geez.bbl.db.type.Book;
import com.geez.bbl.util.Consumer;
import com.geez.bbl.util.FileUtils;
import com.geez.bbl.util.ProjectResources;
import org.dom4j.*;
import sun.misc.IOUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created with IntelliJ IDEA.
 *
 * @author biniam.gebremichael
 * @since 12/27/12
 */
public class Linking {

    static File linkFile = ProjectResources.getResourceFile("linking", "chapters.csv");
    static File xmlFiles = ProjectResources.getResourceFile("linking", "ref");
    static Map<String, Book> books = initMap();
    StringBuilder inserts = new StringBuilder();

    public Linking() throws DocumentException {
        //printWget();
        parseFile();
           FileUtils.save(ProjectResources.getResourceFile("linking", "linking.sql"),inserts.toString());
    }

    private void parseFile() throws DocumentException {
        Pattern regex = Pattern.compile("href=([^>]+)");
        for (File file : xmlFiles.listFiles()) {
            int srcBook = Integer.valueOf(file.getName().substring(0, file.getName().indexOf("_")));
            int srcChapter = Integer.valueOf(file.getName().substring(file.getName().indexOf("_") + 1, file.getName().indexOf(".")));
            String content = filterRef(file);
            Matcher regexMatcher = regex.matcher(content);
            String xml = regexMatcher.replaceAll("href=\"$1\"");
            Document doc = DocumentHelper.parseText(xml);
            for (Object o : doc.getRootElement().elements()) {
                Element e = (Element) o;
                Element dd = e.element("dd");
                Element a = dd.element("a");
                if (a != null) {
                    Attribute attribute = a.attribute("href");
                    String src = attribute.getData().toString();
                    int srcVerse = Integer.valueOf(src.substring(src.lastIndexOf(":") + 1, src.lastIndexOf("/")));
                    // System.out.println("src = " + src);
                    for (Object o1 : dd.element("span").elements("span")) {
                        try {
                            Element r = (Element) o1;
                            String refData = r.getData().toString();
                            String[] parserRefData = refData.split(":");
                            int desBook = books.get(parserRefData[0]).getId();
                            int desChap = Integer.valueOf(parserRefData[1]);
                            String desVerse = parserRefData[2];
                            int sDesVerse, eDesVerse;
                            if (desVerse.contains("-")) {
                                String[] desVerses = desVerse.split("-");
                                sDesVerse = Integer.valueOf(desVerses[0]);
                                eDesVerse = Integer.valueOf(desVerses[1]);
                            } else {
                                sDesVerse = Integer.valueOf(desVerse);
                                eDesVerse = sDesVerse;
                            }
                            LinkObject link = new LinkObject(srcBook, srcChapter, srcVerse, desBook, desChap, sDesVerse, eDesVerse);
                   //         System.out.println(link);
                   //         System.out.println(refData);
                            inserts.append(link);
                            inserts.append(";\n");
                        } catch (Exception e2) {
                            e2.printStackTrace();
                        }
                    }
                }

            }

            System.out.println("file = " + xml);
        }
    }

    private void printWget() {
        for (Book book : init()) {
            for (int i = 1; i < book.getChapterSize(); i++) {
                System.out.println("wget http://drupalbible.org/bible/1/" + book.getEnAbb() + "/" + i + " -o " + book.getId() + "_" + i + ".xml");
            }
        }
    }

    private String filterRef(File file) {
        String content = FileUtils.getFileContent(file, false);
        int start = content.indexOf("<dl class=\"bible-chapter-content\">");
        int end = content.indexOf("</dl>");
        System.out.println("start = " + start);
        System.out.println("end = " + end);
        if (start > end) {
            System.exit(0);
        }
        return content.substring(start, end + 5);
    }


    private static Map<String, Book> initMap() {
        final Map<String, Book> books = new HashMap<String, Book>();
        final AtomicInteger chapter = new AtomicInteger(1);
        FileUtils.processFile(linkFile, new Consumer<String>() {
            @Override
            public void consume(String message) {
                String[] var = message.split("\\|");
                books.put(var[0], new Book(chapter.getAndIncrement(), "", var[1], var[0], Integer.valueOf(var[3]), 0));
            }
        });
        return books;
    }

    private static List<Book> init() {
        final List<Book> books = new ArrayList<Book>();
        final AtomicInteger chapter = new AtomicInteger(1);
        FileUtils.processFile(linkFile, new Consumer<String>() {
            @Override
            public void consume(String message) {
                String[] var = message.split("\\|");
                books.add(new Book(chapter.getAndIncrement(), "", var[1], var[0], Integer.valueOf(var[3]), 0));
            }
        });
        return books;
    }

    public static void main(String[] args) throws DocumentException {
        new Linking();
    }
}
